<template>
  <view class="auth-container">
    <!-- 登录表单 -->
    <view v-if="isLogin" class="form-container">
      <view class="form-wrapper">
        <view class="form-header">
          <text class="form-title">欢迎回来</text>
          <text class="form-subtitle">Welcome back</text>
        </view>
        
        <view class="logo-container">
          <view class="logo-wrapper">
            <image class="logo-image" src="/static/logo.png" mode="aspectFit"></image>
          </view>
        </view>
        
        <view class="form-content">
          <view class="form-item">
            <view class="input-wrapper">
              <text class="input-icon">👤</text>
              <input 
                class="form-input" 
                type="text" 
                placeholder="请输入账号" 
                v-model="loginForm.account"
                @keydown.enter="handleLogin"
              />
            </view>
          </view>
          <view class="form-item">
            <view class="input-wrapper">
              <text class="input-icon">🔒</text>
              <input 
                class="form-input" 
                type="password" 
                placeholder="请输入密码" 
                v-model="loginForm.password"
                @keydown.enter="handleLogin"
              />
            </view>
          </view>
          
          <view class="form-item">
            <button class="form-button" @click="handleLogin">登录</button>
          </view>
          
          <view class="form-footer">
            <text class="switch-text" @click="switchToRegister">没有账号？立即注册</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 注册表单 -->
    <view v-else class="form-container">
      <view class="form-wrapper">
        <view class="form-header">
          <text class="form-title">创建账户</text>
          <text class="form-subtitle">Create an account</text>
        </view>
        
        <view class="logo-container">
          <view class="logo-wrapper">
            <image class="logo-image" src="/static/logo.png" mode="aspectFit"></image>
          </view>
        </view>
        
        <view class="form-content">
          <view class="form-item">
            <view class="input-wrapper">
              <text class="input-icon">👤</text>
              <input 
                class="form-input" 
                type="text" 
                placeholder="请输入账号" 
                v-model="registerForm.account"
                @keydown.enter="handleRegister"
              />
            </view>
          </view>
          <view class="form-item">
            <view class="input-wrapper">
              <text class="input-icon">🔒</text>
              <input 
                class="form-input" 
                type="password" 
                placeholder="请输入密码" 
                v-model="registerForm.password"
                @keydown.enter="handleRegister"
              />
            </view>
          </view>
          <view class="form-item">
            <view class="input-wrapper">
              <text class="input-icon">🔒</text>
              <input 
                class="form-input" 
                type="password" 
                placeholder="请确认密码" 
                v-model="registerForm.confirmPassword"
                @keydown.enter="handleRegister"
              />
            </view>
          </view>
          
          <view class="form-item">
            <button class="form-button" @click="handleRegister">注册</button>
          </view>
          
          <view class="form-footer">
            <text class="switch-text" @click="switchToLogin">已有账号？立即登录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { login, register } from '@/api/user/index.ts'
import { getUserInfo, showToast, getDefaultAccount, navigateTo } from '@/utils/index.ts'
import websocket from '@/utils/websocket'

// 登录/注册状态切换
const isLogin = ref(true)

// 登录表单数据
const loginForm = reactive({
  account: getDefaultAccount(),
  password: process.env.NODE_ENV === 'development' ? 'f' : ''
})

// 注册表单数据
const registerForm = reactive({
  account: '',
  password: '',
  confirmPassword: ''
})

// 切换到注册
const switchToRegister = () => {
  isLogin.value = false
}

// 切换到登录
const switchToLogin = () => {
  isLogin.value = true
}

// 处理登录
const handleLogin = async () => {
  if (!loginForm.account || !loginForm.password) {
    showToast('请填写完整信息')
    return
  }

  uni.showLoading({
    title: '登录中...'
  })

  try {
    const res = await login(loginForm)
    
    if (res.code === 200) {
      // 存储用户信息和token
      uni.setStorageSync('userInfo', res.data.user)
      uni.setStorageSync('token', res.data.token)
      
      // 初始化WebSocket连接（不再需要传递userId）
      websocket.init(() => {
        console.log('WebSocket连接成功');
      })

      // 登录成功后跳转到主应用入口页
      // 对于自定义tabbar应用，使用 redirectTo 替代 reLaunch
      uni.redirectTo({
        url: '/pages/index/index'
      })
      uni.hideLoading()
    }
  } catch (error) {
    uni.hideLoading()
    console.error('登录异常:', error)
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerForm.account || !registerForm.password) {
    showToast('请填写必要信息')
    return
  }
  
  if (registerForm.password !== registerForm.confirmPassword) {
    showToast('两次输入的密码不一致')
    return
  }
  
  try {
    const res = await register({
      account: registerForm.account,
      password: registerForm.password
    })
    
    if (res.code === 200) {
      showToast('注册成功', 'success')
      
      // 切换到登录
      setTimeout(() => {
        switchToLogin()
      }, 0)
    }
  } catch (error) {
    console.error('注册请求失败:', error)
  }
}
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

.auth-container::before {
  content: "";
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
  transform: rotate(30deg);
}

.form-container {
  width: 100%;
  max-width: 450rpx;
  position: relative;
  z-index: 2;
}

.form-wrapper {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 50rpx 40rpx;
  box-shadow: 0 25rpx 50rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.form-title {
  font-size: 42rpx;
  font-weight: 700;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
  letter-spacing: 1rpx;
}

.form-subtitle {
  font-size: 26rpx;
  color: #999;
  font-weight: 300;
}

.logo-container {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.logo-wrapper {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  box-shadow: 0 10rpx 25rpx rgba(161, 196, 253, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: white;
}

.logo-image {
  width: 100rpx;
  height: 100rpx;
  margin-left: 20rpx;
}

.logo-placeholder {
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #a1c4fd, #c2e9fb);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 10rpx 25rpx rgba(161, 196, 253, 0.4);
}

.logo-text {
  font-size: 48rpx;
  color: white;
  font-weight: bold;
}

.form-content {
  margin-top: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 30rpx;
  font-size: 32rpx;
  color: #999;
  z-index: 2;
}

.form-input {
  width: 100%;
  height: 90rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  padding: 0 30rpx 0 80rpx;
  font-size: 30rpx;
  background-color: #fafafa;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #a1c4fd;
  background-color: #ffffff;
  box-shadow: 0 0 0 2rpx rgba(161, 196, 253, 0.2);
}

.form-button {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(90deg, #a1c4fd, #c2e9fb);
  border-radius: 12rpx;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  box-shadow: 0 10rpx 25rpx rgba(161, 196, 253, 0.4);
  transition: all 0.3s ease;
}

.form-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 5rpx 15rpx rgba(161, 196, 253, 0.4);
}

.form-footer {
  text-align: center;
  margin-top: 30rpx;
}

.switch-text {
  color: #6a93cb;
  font-weight: 500;
  font-size: 28rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.switch-text:hover {
  color: #4a6fa6;
  text-decoration: underline;
}
</style>